<template>
  <div class="claim-report-form-container">
    <!-- 页面标题与返回按钮 -->
    <el-page-header :content="pageTitle" @back="goBack" class="page-header" />

    <!-- 报案表单卡片 -->
    <el-card shadow="hover" class="form-card">
      <!-- 投保人保单查询模块 -->
      <div class="policy-search-section" v-if="!isDetail">
        <el-divider content-position="left">投保人保单查询</el-divider>
        <el-form ref="searchFormRef" :model="searchForm" label-width="120px" class="search-form" inline>
          <el-form-item label="投保人姓名" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入投保人姓名" clearable maxlength="64" />
          </el-form-item>
          <el-form-item label="投保人手机号" prop="phone">
            <el-input v-model="searchForm.phone" placeholder="请输入11位手机号" clearable maxlength="11"
              @input="formatPhone" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchPolicy" :loading="loading">查询保单</el-button>
            <el-button @click="resetSearchForm">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 保单查询结果弹窗 -->
        <el-dialog v-model="policyDialogVisible" title="保单查询结果" width="70%" :before-close="handleDialogClose">
          <el-table :data="policyList" border stripe size="small" style="width: 100%" @row-click="selectPolicy"
            :row-class-name="tableRowClassName">
            <el-table-column label="保单编号" prop="policyId" align="center" min-width="160" />
            <el-table-column label="险种名称" prop="insuranceCoverageName" align="center" min-width="180" />
            <el-table-column label="投保项目" prop="insuranceSubject" align="center" min-width="120" />
            <el-table-column label="保险期间" align="center" min-width="200">
              <template #default="scope">
                {{ scope.row.startDate }} 至 {{ scope.row.endDate }}
              </template>
            </el-table-column>
            <el-table-column label="总保额(元)" prop="sumInsured" align="center" min-width="120" />
            <el-table-column label="保单状态" align="center" min-width="120">
              <template #default="scope">
                <el-tag :type="getPolicyStatusTagType(scope.row.policyStatus)">
                  {{ getPolicyStatusText(scope.row.policyStatus) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="policyDialogVisible = false">关闭</el-button>
            </div>
          </template>
        </el-dialog>
      </div>

      <!-- 报案表单 -->
      <el-form ref="reportFormRef" :model="reportForm" label-width="160px" :rules="formRules" class="report-form"
        :disabled="isDetail || loading" validate-on-rule-change style="margin-top: 24px">
        <!-- 1. 报案号（仅编辑/详情显示） -->
        <el-form-item v-if="isEdit || isDetail" label="报案号">
          <el-input v-model="reportForm.reportNo" readonly placeholder="系统自动生成" class="readonly-input" />
        </el-form-item>

        <!-- 2. 保单编号（必选） -->
        <el-form-item label="保单编号" prop="policyId">
          <el-input v-model="reportForm.policyId" placeholder="请输入关联的保单编号（可通过上方查询获取）" clearable :readonly="isDetail"
            @blur="handlePolicyIdBlur" />
        </el-form-item>

        <!-- 3. 报案时间（仅编辑/详情显示） -->
        <el-form-item v-if="isEdit || isDetail" label="报案时间">
          <el-input v-model="reportForm.reportTime" readonly class="readonly-input" />
        </el-form-item>

        <!-- 4. 灾祸类型（必选） -->
        <el-form-item label="灾祸类型" prop="disasterType">
          <el-select v-model="reportForm.disasterType" placeholder="请选择灾祸类型" clearable :disabled="isDetail">
            <el-option label="暴雨" value="1" />
            <el-option label="洪水" value="2" />
            <el-option label="病虫害" value="3" />
            <el-option label="疫病" value="4" />
            <el-option label="其他" value="5" />
          </el-select>
        </el-form-item>

        <!-- 5. 灾祸发生时间（必选） -->
        <el-form-item label="灾祸发生时间" prop="disasterOccurTime">
          <el-date-picker v-model="reportForm.disasterOccurTime" type="datetime" placeholder="请选择灾祸发生时间"
            value-format="YYYY-MM-DD HH:mm:ss" clearable :disabled="isDetail" :disabled-date="disabledDisasterDate" />
        </el-form-item>

        <!-- 6. 灾祸发生地点（必选） -->
        <el-form-item label="灾祸发生地点" prop="disasterLocation">
          <el-input v-model="reportForm.disasterLocation" placeholder="请输入精确地点（如：XX村3组东地块）" clearable
            :readonly="isDetail" />
        </el-form-item>

        <!-- 7. 损失情况描述（必选） -->
        <el-form-item label="损失情况描述" prop="lossDescription">
          <el-input v-model="reportForm.lossDescription" type="textarea" rows="4" placeholder="请详细描述损失情况" clearable
            :readonly="isDetail" />
        </el-form-item>

        <!-- 8. 预估损失金额（可选） -->
        <el-form-item label="预估损失金额（元）" prop="lossEstimate">
          <el-input v-model="reportForm.lossEstimate" placeholder="请输入非负数字（保留2位小数）" type="number" step="0.01" min="0"
            clearable :readonly="isDetail" />
        </el-form-item>

        <!-- 9. 报案人姓名（必选） -->
        <el-form-item label="报案人姓名" prop="reporterName">
          <el-input v-model="reportForm.reporterName" placeholder="请输入报案人姓名" clearable :readonly="isDetail" />
        </el-form-item>

        <!-- 10. 报案人联系电话（必选） -->
        <el-form-item label="报案人联系电话" prop="reporterPhone">
          <el-input v-model="reportForm.reporterPhone" placeholder="请输入11位手机号码" maxlength="11" clearable
            :readonly="isDetail" />
        </el-form-item>

        <!-- 11. 报案渠道（必选） -->
        <el-form-item label="报案渠道" prop="reportChannel">
          <el-select v-model="reportForm.reportChannel" placeholder="请选择报案渠道" clearable :disabled="isDetail">
            <el-option label="电话" value="1" />
            <el-option label="APP" value="2" />
            <el-option label="线下网点" value="3" />
            <el-option label="业务员代报" value="4" />
          </el-select>
        </el-form-item>

        <!-- 12. 受理员工号（必选，非详情页显示）- 改为报案员选择 -->
        <el-form-item label="受理员工号（报案员）" prop="reportWorkNo" v-if="!isDetail">
          <el-select v-model="reportForm.reportWorkNo" placeholder="请选择报案员" clearable
            :disabled="isDetail || isLoadingReporter" :loading="isLoadingReporter" filterable>
            <el-option v-for="item in reporterOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- 13. 报案状态（仅编辑/详情显示）- 整合状态标签组件 -->
        <el-form-item v-if="isEdit || isDetail" label="报案状态">
          <el-tag :type="getStatusTagType(reportForm.reportStatus)" :icon="getStatusIcon(reportForm.reportStatus)"
            size="small">
            {{ getStatusText(reportForm.reportStatus) }}
          </el-tag>
        </el-form-item>

        <!-- 14. 驳回原因（仅状态为已驳回时显示） -->
        <el-form-item label="驳回原因" v-if="(isEdit || isDetail) && reportForm.reportStatus === 9">
          <el-input v-model="reportForm.rejectReason" type="textarea" rows="3" readonly placeholder="无"
            class="readonly-input" />
        </el-form-item>

        <!-- 15. 受理时间（仅编辑/详情显示） -->
        <el-form-item v-if="isEdit || isDetail" label="受理时间">
          <el-input v-model="reportForm.handleTime" readonly class="readonly-input" />
        </el-form-item>

        <!-- 16. 表单操作按钮 -->
        <el-form-item class="form-btn-group">
          <el-button @click="goBack" size="default">取消</el-button>
          <el-button v-if="!isDetail" type="primary" @click="submitForm" size="default" :loading="submitting">
            {{ isEdit ? '更新报案' : '提交报案' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import axios from "axios";
import hxxp from '@/utils/hxxp.js'
// 导入状态标签所需图标
import { Check, Clock, Close, Flag, Hourglass, Inbox, FileCheck, CircleCheck } from '@element-plus/icons-vue'

const checkDisasterTime = (rule, value, callback) => {
  if (!value) return callback()
  const disasterTime = new Date(value).getTime()
  const reportTime = isEdit.value
    ? new Date(reportForm.reportTime).getTime()
    : new Date().getTime()

  if (disasterTime > reportTime) {
    callback(new Error('灾祸发生时间不能晚于报案时间'))
  } else {
    callback()
  }
}

// 校验受灾时间是否在保单保险期间内
const checkDisasterInPolicyPeriod = (rule, value, callback) => {
  // 若未选择保单或未填写受灾时间，先不校验（避免提前报错）
  if (!reportForm.policyId || !value) {
    return callback();
  }
  // 若未获取到保单期间（可能手动输入保单号，未通过查询选择）
  if (!currentPolicyPeriod.startDate || !currentPolicyPeriod.endDate) {
    return callback(new Error('请通过「投保人保单查询」选择有效保单，以校验保险期间'));
  }

  // 格式化时间为时间戳（统一对比格式）
  const disasterTime = new Date(value).getTime();
  const policyStartTime = new Date(currentPolicyPeriod.startDate).getTime();
  const policyEndTime = new Date(currentPolicyPeriod.endDate).getTime();

  // 校验逻辑：受灾时间需 ≥ 保单开始时间 且 ≤ 保单结束时间
  if (disasterTime < policyStartTime || disasterTime > policyEndTime) {
    callback(new Error(`灾祸发生时间需在保单期间内（${currentPolicyPeriod.startDate} 至 ${currentPolicyPeriod.endDate}）`));
  } else {
    callback();
  }
};

// 日期格式化工具函数
const formatDate = (date, fmt = 'yyyy-MM-dd HH:mm:ss') => {
  if (!date) return ''
  if (typeof date === 'string') {
    date = new Date(date)
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'q+': Math.floor((date.getMonth() + 3) / 3),
    'S': date.getMilliseconds()
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

// 本地缓存工具
const FormStorage = {
  saveFormData(key, data) {
    try {
      localStorage.setItem(`claim_form_${key}`, JSON.stringify(data))
    } catch (e) {
      console.warn('表单数据缓存失败:', e)
    }
  },

  getFormData(key) {
    try {
      const data = localStorage.getItem(`claim_form_${key}`)
      return data ? JSON.parse(data) : null
    } catch (e) {
      console.warn('获取表单缓存数据失败:', e)
      return null
    }
  },

  clearFormData(key) {
    localStorage.removeItem(`claim_form_${key}`)
  }
}

// 路由与表单引用
const route = useRoute()
const router = useRouter()
const reportFormRef = ref(null)  // 报案表单引用
const searchFormRef = ref(null)  // 查询表单引用

// 状态控制
const loading = ref(false)
const submitting = ref(false)
const formCacheKey = computed(() => `report_${route.query.reportNo || 'new'}`)

// 场景判断（新增/编辑/详情）
const isEdit = computed(() => !!route.query.reportNo && !route.query.view)
const isDetail = computed(() => !!route.query.reportNo && route.query.view === 'detail')
const pageTitle = computed(() => {
  if (isEdit.value) return '编辑报案'
  if (isDetail.value) return '报案详情'
  return '新增报案'
})

// 表单数据模型
const reportForm = reactive({
  reportNo: '',          // 报案号（后端生成）
  policyId: '',          // 保单编号
  reportTime: formatDate(new Date()), // 报案时间
  disasterType: '',      // 灾祸类型（1-暴雨/2-洪水等）
  disasterOccurTime: '', // 灾祸发生时间
  disasterLocation: '',  // 灾祸发生地点
  lossDescription: '',   // 损失情况描述
  lossEstimate: '',      // 预估损失金额
  reporterName: '',      // 报案人姓名
  reporterPhone: '',     // 报案人电话
  reportChannel: '',     // 报案渠道（1-电话等）
  reportStatus: 1,       // 报案状态（默认待调度）
  rejectReason: '',      // 驳回原因
  handleTime: '',        // 受理时间
  reportWorkNo: ''       // 受理员工号（报案员）
})

// 保单查询表单数据
const searchForm = reactive({
  name: '',  // 投保人姓名
  phone: ''  // 投保人手机号
})

// 保单查询相关变量
const policyDialogVisible = ref(false)  // 保单弹窗显示状态
const policyList = ref([])              // 保单查询结果列表
const selectedPolicy = ref(null)        // 当前选中的保单
const lastSearchParams = ref({})        // 上次查询参数，用于防重复查询

// 存储当前保单的保险起止时间（用于时间校验）
const currentPolicyPeriod = reactive({
  startDate: '', // 保单开始时间
  endDate: ''    // 保单结束时间
});

// 报案员（职位编码PTN004）相关变量
const reporterOptions = ref([]); // 报案员列表（工号+姓名）
const isLoadingReporter = ref(false); // 报案员列表加载状态

// 完整报案状态映射（包含text、type、icon，对应1-9所有状态）
const statusConfig = {
  1: { text: '待调度', type: 'info', icon: Clock },
  2: { text: '待查勘', type: 'primary', icon: Check },
  3: { text: '待立案', type: 'processing', icon: Inbox },
  4: { text: '已立案', type: 'success', icon: Flag },
  5: { text: '待理算', type: 'warning', icon: Hourglass },
  6: { text: '待核赔', type: 'warning', icon: FileCheck },
  7: { text: '待结案', type: 'success', icon: CircleCheck },
  8: { text: '已结案', type: 'success', icon: CircleCheck },
  9: { text: '已驳回', type: 'danger', icon: Close }
}

// 保单状态映射
const policyStatusMap = {
  1: '待生效',
  2: '已生效',
  3: '已退保',
  4: '已过期'
}
const policyStatusTagType = {
  1: 'processing',
  2: 'success',
  3: 'warning',
  4: 'info'
}

// Axios实例配置与拦截器
const reportAxios = hxxp

// 使用hxxp替代policyAxios
const policyAxios = hxxp


// 表单校验规则
const formRules = reactive({
  policyId: [
    { required: true, message: '请输入保单编号', trigger: 'blur' },
    { min: 6, max: 32, message: '保单编号长度需在6-32位之间', trigger: 'blur' }
  ],
  disasterType: [
    { required: true, message: '请选择灾祸类型', trigger: 'change' }
  ],
  disasterOccurTime: [
    { required: true, message: '请选择灾祸发生时间', trigger: 'change' },
    { validator: checkDisasterTime, trigger: 'change' },
    // 校验受灾时间在保险期间内
    { validator: checkDisasterInPolicyPeriod, trigger: 'change' }
  ],
  disasterLocation: [
    { required: true, message: '请输入灾祸发生地点', trigger: 'blur' },
    { min: 5, max: 255, message: '地点描述需在5-255字符之间', trigger: 'blur' }
  ],
  lossDescription: [
    { required: true, message: '请描述损失情况', trigger: 'blur' },
    { min: 10, max: 1000, message: '损失描述需在10-1000字符之间', trigger: 'blur' }
  ],
  lossEstimate: [
    { pattern: /^\d+(\.\d{1,2})?$/, message: '需为非负数字且最多保留2位小数', trigger: 'blur' }
  ],
  reporterName: [
    { required: true, message: '请输入报案人姓名', trigger: 'blur' },
    { min: 2, max: 64, message: '姓名需在2-64字符之间', trigger: 'blur' }
  ],
  reporterPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的11位手机号码', trigger: 'blur' }
  ],
  reportChannel: [
    { required: true, message: '请选择报案渠道', trigger: 'change' }
  ],
  reportWorkNo: [
    { required: true, message: '请选择报案员', trigger: 'change' }
  ]
})

// 格式化手机号输入（移除非数字字符）
const formatPhone = (value) => {
  if (value) {
    searchForm.phone = value.replace(/\D/g, '')
  }
}

// 执行保单查询
const searchPolicy = async () => {
  // 检查是否与上次查询参数相同
  const currentParams = { ...searchForm }
  if (JSON.stringify(currentParams) === JSON.stringify(lastSearchParams.value)) {
    ElMessage.info('已查询过相同条件的保单')
    policyDialogVisible.value = true
    return
  }

  if (!searchForm.name && !searchForm.phone) {
    ElMessage.warning('请至少输入姓名或手机号')
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中，请稍候...',
    background: 'rgba(255, 255, 255, 0.7)'
  })

  try {
    const res = await policyAxios.get('/aiFarmerInsured/searchPolicy', {
      params: {
        name: searchForm.name,
        phone: searchForm.phone,
        policyStatus: 2 // 只查询已生效保单
      }
    })

    lastSearchParams.value = { ...currentParams }

    if (res.code === 100200) {
      if (res.data && res.data.length > 0) {
        policyList.value = res.data
        policyDialogVisible.value = true
      } else {
        ElMessage.info(res.msg || '未查询到相关保单')
      }
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  } catch (err) {
    const errorMsg = err.response
      ? `服务器错误(${err.response.status})`
      : '网络连接异常'
    ElMessage.error(`保单查询失败：${errorMsg}`)
  } finally {
    loadingInstance.close()
  }
}

// 重置查询表单
const resetSearchForm = () => {
  searchForm.name = ''
  searchForm.phone = ''
  lastSearchParams.value = {}
  if (searchFormRef.value) {
    searchFormRef.value.clearValidate()
  }
}

// 选择保单（行点击事件）
const selectPolicy = (row) => {
  selectedPolicy.value = row
  reportForm.policyId = row.policyId
  // 保存当前保单的保险期间到变量中
  currentPolicyPeriod.startDate = row.startDate;
  currentPolicyPeriod.endDate = row.endDate;
  policyDialogVisible.value = false
  ElMessage.success(`已选择保单：${row.policyId}`)
  saveFormCache()
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  return row.policyId === reportForm.policyId ? 'table-row-selected' : 'table-row-hover'
}

// 状态工具函数
const getStatusText = (status) => statusConfig[status]?.text || '未知状态'
const getStatusTagType = (status) => statusConfig[status]?.type || 'default'
const getStatusIcon = (status) => statusConfig[status]?.icon || null
const getPolicyStatusText = (status) => policyStatusMap[status] || '未知状态'
const getPolicyStatusTagType = (status) => policyStatusTagType[status] || 'default'

// 弹窗关闭处理
const handleDialogClose = () => {
  policyDialogVisible.value = false
}

// 根据保单号查询保险期间（用于手动输入保单号时的校验）
const getPolicyPeriodByPolicyId = async (policyId) => {
  if (!policyId) return;
  try {
    const res = await policyAxios.get('/aiFarmerInsured/getPolicyPeriod', {
      params: { policyId: policyId }
    });
    if (res.code === 100200 && res.data) {
      // 更新当前保单期间变量
      currentPolicyPeriod.startDate = res.data.startDate;
      currentPolicyPeriod.endDate = res.data.endDate;
      // 触发受灾时间校验
      if (reportForm.disasterOccurTime && reportFormRef.value) {
        reportFormRef.value.validateField('disasterOccurTime');
      }
    } else {
      // 未查询到保单时清空期间，触发校验报错
      currentPolicyPeriod.startDate = '';
      currentPolicyPeriod.endDate = '';
      ElMessage.warning('未查询到该保单的保险期间，请确认保单号是否正确');
    }
  } catch (err) {
    currentPolicyPeriod.startDate = '';
    currentPolicyPeriod.endDate = '';
    ElMessage.error('查询保单期间失败：' + (err.response?.status || '网络错误'));
  }
};

// 处理保单号输入框失焦事件（手动输入时查询保险期间）
const handlePolicyIdBlur = () => {
  if (reportForm.policyId && (!currentPolicyPeriod.startDate || !currentPolicyPeriod.endDate)) {
    getPolicyPeriodByPolicyId(reportForm.policyId);
  }
};

// 限制灾祸发生时间选择范围
const disabledDisasterDate = (date) => {
  // 未获取保单期间时，只禁止未来日期
  if (!currentPolicyPeriod.startDate) {
    return date.getTime() > new Date().getTime();
  }
  // 已获取保单期间时，禁止超出保单范围和未来日期
  const start = new Date(currentPolicyPeriod.startDate).getTime();
  const end = new Date().getTime();
  return date.getTime() < start || date.getTime() > end;
};

// 获取报案员列表（职位编码PTN004）
const getReporterList = async () => {
  if (isLoadingReporter.value) return;
  isLoadingReporter.value = true;
  try {
    // 调用员工接口，筛选职位编码为PTN004的报案员
    const res = await policyAxios.get('/aiStaffUser/worker', {
      params: {
        positionCode: 'PTN004' // 报案员职位编码
      }
    });
    if (res.code === 100200) {
      // 格式化选项：显示"姓名（工号）"，值为工号
      reporterOptions.value = res.data.map(item => ({
        label: `${item.realName}（${item.workNo}）`,
        value: item.workNo
      }));
    } else {
      ElMessage.warning('获取报案员列表失败：' + (res.msg || '数据异常'));
    }
  } catch (err) {
    ElMessage.error('获取报案员列表异常：' + (err.response?.status || '网络错误'));
  } finally {
    isLoadingReporter.value = false;
  }
};

// 获取报案详情
const getReportDetail = async (reportNo) => {
  if (loading.value) return
  loading.value = true

  try {
    const res = await reportAxios.get(`/aiClaimReport/${reportNo}`)
    if (res.code === 100200 && res.data) {
      const data = res.data
      const formatLocalDateTime = (timeStr) => {
        if (!timeStr) return ''
        return new Date(timeStr).toLocaleString('zh-CN', {
          year: 'numeric', month: '2-digit', day: '2-digit',
          hour: '2-digit', minute: '2-digit', second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      }

      // 赋值表单数据
      reportForm.reportNo = data.reportNo || ''
      reportForm.policyId = data.policyId || ''
      reportForm.reportTime = formatLocalDateTime(data.reportTime)
      reportForm.disasterType = data.disasterType || ''
      reportForm.disasterOccurTime = formatLocalDateTime(data.disasterOccurTime)
      reportForm.disasterLocation = data.disasterLocation || ''
      reportForm.lossDescription = data.lossDescription || ''
      reportForm.lossEstimate = data.lossEstimate ? data.lossEstimate.toString() : ''
      reportForm.reporterName = data.reporterName || ''
      reportForm.reporterPhone = data.reporterPhone || ''
      reportForm.reportChannel = data.reportChannel || ''
      reportForm.reportStatus = data.reportStatus || 1
      reportForm.rejectReason = data.rejectReason || ''
      reportForm.handleTime = formatLocalDateTime(data.handleTime)
      reportForm.reportWorkNo = data.reportWorkNo || ''

      // 获取保单期间（用于详情页显示时的校验状态保持）
      if (reportForm.policyId) {
        await getPolicyPeriodByPolicyId(reportForm.policyId);
      }

      if (isEdit.value) {
        saveFormCache()
      }
    } else {
      ElMessage.error('获取报案详情失败：' + (res.msg || '数据异常'))
      goBack()
    }
  } catch (err) {
    const errorMsg = err.response
      ? `服务器错误(${err.response.status})`
      : '网络连接异常'
    ElMessage.error(`获取详情异常：${errorMsg}`)
    goBack()
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (submitting.value) {
    ElMessage.warning('正在处理，请不要重复提交')
    return
  }

  if (!reportFormRef.value) return
  try {
    await reportFormRef.value.validate()
  } catch (error) {
    ElMessage.error('表单填写有误，请检查标红字段')
    return
  }

  submitting.value = true
  const loadingInstance = ElLoading.service({
    lock: true,
    text: `${isEdit.value ? '更新' : '提交'}中，请稍候...`,
    background: 'rgba(255, 255, 255, 0.7)'
  })

  try {
    // 处理提交数据
    const submitData = {
      ...reportForm,
      reportTime: reportForm.reportTime.replace(' ', 'T'),
      disasterOccurTime: reportForm.disasterOccurTime.replace(' ', 'T'),
      handleTime: reportForm.handleTime ? reportForm.handleTime.replace(' ', 'T') : undefined,
      lossEstimate: reportForm.lossEstimate ? Number(reportForm.lossEstimate) : null,
      reportNo: isEdit.value ? reportForm.reportNo : undefined,
      reportStatus: isEdit.value ? reportForm.reportStatus : 1,
      rejectReason: reportForm.rejectReason || undefined
    }
    delete submitData.insuredId

    let res
    if (isEdit.value) {
      res = await reportAxios.put(`/aiClaimReport/update/${submitData.reportNo}`, submitData)
    } else {
      res = await reportAxios.post('/aiClaimReport/addReport', submitData)
    }

    if (res.code === 100200) {
      ElMessage.success(isEdit.value ? '更新成功！' : '提交成功！')
      FormStorage.clearFormData(formCacheKey.value)

      // 重置表单
      Object.keys(reportForm).forEach(key => {
        if (key === 'reportTime') {
          reportForm[key] = formatDate(new Date())
        } else if (key === 'reportStatus') {
          reportForm[key] = 1
        } else {
          reportForm[key] = ''
        }
      })

      // 清空保单期间
      currentPolicyPeriod.startDate = '';
      currentPolicyPeriod.endDate = '';

      if (reportFormRef.value) {
        reportFormRef.value.clearValidate()
      }

      // 跳转至报案列表页
      router.push('/claimList');
    } else {
      ElMessage.error(`${isEdit.value ? '更新' : '提交'}失败：${res.msg || '操作异常'}`)
    }
  } catch (err) {
    const errorMsg = err.response
      ? `服务器错误(${err.response.status})`
      : '网络连接异常'
    ElMessage.error(`${isEdit.value ? '更新' : '提交'}异常：${errorMsg}`)
  } finally {
    submitting.value = false
    loadingInstance.close()
  }
}

// 表单缓存相关方法
const saveFormCache = () => {
  if (isDetail.value) return
  const formData = JSON.parse(JSON.stringify(toRaw(reportForm)))
  FormStorage.saveFormData(formCacheKey.value, formData)
}

const loadFormCache = () => {
  if (isEdit.value || isDetail.value) return

  const cachedData = FormStorage.getFormData(formCacheKey.value)
  if (cachedData) {
    Object.keys(cachedData).forEach(key => {
      if (reportForm.hasOwnProperty(key)) {
        reportForm[key] = cachedData[key]
      }
    })
    // 缓存数据加载后重新获取保单期间
    if (reportForm.policyId) {
      getPolicyPeriodByPolicyId(reportForm.policyId);
    }
  }
}

// 返回列表页（修复跳转路径）
const goBack = () => {
  if (!isDetail.value && hasFormData()) {
    if (confirm('表单数据尚未提交，确定要离开吗？')) {
      router.push('/claimList');
    }
  } else {
    router.push('/claimList');
  }
}

// 检查表单是否有数据
const hasFormData = () => {
  return Object.keys(reportForm).some(key => {
    const value = reportForm[key]
    return value !== null && value !== undefined && value !== ''
  })
}

// 页面初始化
onMounted(() => {
  // 每30秒自动保存一次表单数据
  setInterval(() => {
    if (!isDetail.value && !submitting.value) {
      saveFormCache()
    }
  }, 30000)

  // 加载报案员列表
  getReporterList();

  if (isEdit.value || isDetail.value) {
    getReportDetail(route.query.reportNo)
  } else {
    // 新增页面加载缓存数据
    loadFormCache();
  }
})

// 监听表单数据变化，自动保存
watch([
  () => reportForm.policyId,
  () => reportForm.disasterType,
  () => reportForm.disasterOccurTime,
  () => reportForm.reporterName,
  () => reportForm.reporterPhone
], () => {
  if (!isDetail.value && !submitting.value) {
    saveFormCache()
  }
})

// 监听路由变化
watch([() => route.query.reportNo, () => route.query.view],
  ([newReportNo, newView]) => {
    // 重置表单
    Object.keys(reportForm).forEach(key => {
      if (key === 'reportTime') {
        reportForm[key] = formatDate(new Date())
      } else if (key === 'reportStatus') {
        reportForm[key] = 1
      } else {
        reportForm[key] = ''
      }
    })

    // 清空保单期间
    currentPolicyPeriod.startDate = '';
    currentPolicyPeriod.endDate = '';

    if (reportFormRef.value) {
      reportFormRef.value.clearValidate()
    }

    // 清除查询状态
    policyList.value = []
    lastSearchParams.value = {}
    resetSearchForm()

    if (!!newReportNo && (newView === 'detail' || !newView)) {
      getReportDetail(newReportNo)
    }
  },
  { immediate: true }
)

// 页面关闭前提示
window.addEventListener('beforeunload', (e) => {
  if (!isDetail.value && hasFormData() && !submitting.value) {
    e.preventDefault()
    e.returnValue = '表单数据尚未提交，确定要离开吗？'
    return e.returnValue
  }
})
</script>

<style scoped>
.claim-report-form-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;
}

.form-card {
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
}

/* 保单查询区域样式 */
.policy-search-section {
  margin-bottom: 24px;
}

.search-form {
  margin-bottom: 16px;
}

/* 表格行样式 */
.table-row-hover {
  cursor: pointer;
  background-color: #f0f7ff !important;
}

.table-row-selected {
  background-color: #e6f7ff !important;
}

/* 原有表单样式 */
.report-form {
  margin-top: 16px;
}

.el-form-item {
  margin-bottom: 28px;
}

.readonly-input .el-input__inner {
  background-color: #f5f7fa;
  color: #606266;
  cursor: not-allowed;
}

.form-btn-group {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

/* 弹窗底部按钮样式 */
.dialog-footer {
  text-align: right;
}

/* 适配移动端 */
@media (max-width: 768px) {
  .claim-report-form-container {
    padding: 16px;
  }

  .form-card {
    padding: 16px;
  }

  .search-form {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .form-btn-group {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
